import os
import traceback
from faker import Faker
from config.global_variable import ENV_DICT
from config.all_paths import get_root_path
from utils.file_handling.log_handling import logger
from utils.variables_tool.handling_global_variables import extract_and_store_values, substitution_variables,substitution_url
from utils.time_tool.time_control import Getdate,date_to_timestamp

false = False
true = True
fake = Faker(["zh_CN"])
null = None
class RequestSender:
    def send_request(self, s, apiData):
        """
        发送请求
        :param s: requests.s() 实例
        :param apiData: 数据字典
        :return: 响应对象
        """
        # print('session中的头：', s.headers)

        try:
            url = self._process_url(apiData['url'])
            method = apiData['method']
            headers = self._process_headers(s,apiData.get('request_header'))
            params = self._process_data(apiData.get('params'))
            data = self._process_data(apiData.get('data'))
            json_data = self._process_data(apiData.get('json'))
            files = self._process_files(apiData.get('files'))
            testid = apiData.get('id')

            response = s.request(
                method=method,
                url=url,
                # headers=headers,
                params=params,
                data=data,
                json=json_data,
                files=files,
                verify=False,
                timeout=20
            )

            self._log_request_info(url, method, headers, data, json_data, params, files, testid)
            self._process_global_variables(apiData.get('is_global'), response.json())

            return response
        
        except:
            traceback_info = traceback.format_exc()
            logger.debug(traceback_info)

    def _process_url(self, url):
        env_url = ENV_DICT.get('url')
        if not url.startswith('http'):
            url = env_url + url
        return substitution_url(url)


    def _process_headers(self,s, headers):
        if headers:
            headers = eval(headers)
            s.headers.update(headers)
            return s.headers
        return s.headers

    def _process_data(self, data):
        if data:
            return substitution_variables(eval(data))
        return None


    def _process_files(self, files):
        if files:
            files = eval(files)
            file_path = os.path.join(get_root_path(), 'files', list(files.keys())[0], list(files.values())[0])
            return {'file': (os.path.basename(file_path), open(file_path, 'rb'))}
        return None


    def _process_global_variables(self, is_global, response_json):
        if is_global:
            extract_and_store_values(response_json, eval(is_global))

    def _log_request_info(self, url, method, headers, data, json_data, params, files, testid):
        logger.info(f"接口的id：{testid}")
        logger.info(f"接口请求的地址：{url}")
        logger.info(f"接口请求的方法：{method}")
        logger.info(f"接口请求头：%s", headers)
        logger.info(f"接口请求data：%s", data)
        logger.info(f"接口请求json_data：%s", json_data)
        logger.info(f"接口请求params：%s", params)
        logger.info(f"接口请求files：%s", files)
